package com.ssd.nbgroup;

import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by kzhou on 2015/4/22.
 */
public class HelperClazz {
    private static final String DEFAULT_TEXT_CONTENT_TYPE = "text/plain; charset=utf8";
    private static final String DEFAULT_JSON_CONTENT_TYPE = "application/json; charset=utf8";

    //获取当前日期
    public static String getCurrentDate() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    //获取当前时间
    public static String getCurrentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 获取当前日期是星期几
     *
     * @param year,int month,int date
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(int year, int month, int date) {
        String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
        GregorianCalendar gc = new GregorianCalendar();
        gc.set(year, month - 1, date);
        int w = gc.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }

    //url中文编码
    public static String encode(String s) {
        try {
            return URLEncoder.encode(s, "utf8");
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    //url中文解码
    public static String decode(String s) {
        try {
            return URLDecoder.decode(s, "utf8");
        } catch (Exception e) {
            return "";
        }
    }

    //获得登陆信息id
    //flag==0 is ID;flag==1 is Name;==2 orgId;==3orgName
    public static String getLoginInfo(HttpServletRequest request, int idx) {
        HttpSession session = request.getSession();
        String sess = (String) session.getAttribute("mxoa_login");

        if (sess != null) {
            String[] loginInfos = sess.split("@");
            return loginInfos[idx];
        } else {
            return "";
        }

    }

    //生成随机名称，用于上传文件命名
    public static String getRandomName() {
        Random r = new Random();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
        StringBuffer sb = new StringBuffer();
        sb.append(r.nextInt(100));
        sb.append(r.nextInt(100));
        sb.append("_");
        sb.append(sdf.format(new Date()));
        sb.append("_");
        sb.append(r.nextInt(100));
        sb.append(r.nextInt(100));
        return sb.toString();
    }

    //获得文件名后缀
    public static String getFileExt(String fileName) {
        int idx = fileName.lastIndexOf(".");
        String ext = null;
        if (idx != -1) {
            ext = fileName.substring(idx + 1);
            if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg")) {
                return ext;
            }
        }
        return ext;
    }

    public static String null2String(String o) {
        if (o == null) {
            return "";
        } else {
            return o;
        }
    }

    //response返回内容
    public static void renderText(HttpServletResponse response, String text) {
        PrintWriter writer = null;
        try {
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType(DEFAULT_TEXT_CONTENT_TYPE);
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    //response返回内容
    public static void renderJson(HttpServletResponse response, String text) {
        PrintWriter writer = null;
        try {
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType(DEFAULT_JSON_CONTENT_TYPE);
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    public static boolean isEmpty(Object o) {
        return StringUtils.isEmpty(o);
    }

    /**
     * 将网络图片进行Base64位编码
     *
     * @param  ，如http://.....xx.jpg
     * @return
     */
    public static String encodeImgageToBase64(URL imageUrl) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        ByteArrayOutputStream outputStream = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageUrl);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
    }

    /**
     * 将本地图片进行Base64位编码
     *
     * @param  ，如http://.....xx.jpg
     * @return
     */
    public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        ByteArrayOutputStream outputStream = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
    }

    /**
     * 将Base64位编码的图片进行解码，并保存到指定目录
     *
     * @param base64 base64编码的图片信息
     * @return
     */
    public static void decodeBase64ToImage(String base64, String path, String imgName) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            FileOutputStream write = new FileOutputStream(new File(path
                    + imgName));
            byte[] decoderBytes = decoder.decodeBuffer(base64);
            write.write(decoderBytes);
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean isTodayDate(String date1) {
        if (date1 == null) {
            return false;
        }
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
//        String hehe = df.format( now );
        String hehe = df1.format(now) + " 16:00:00";
        Date today4 = null;
        Date targetDate = null;
//        Date date = null;
        try {
            today4 = df2.parse(hehe);
            targetDate = df2.parse(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return targetDate.getTime() > today4.getTime() ? false : true;
    }
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
           //  设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept-Charset", "utf-8");

            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                   in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


}
